/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xui_lib.component.imageview.edit;

import ohos.agp.components.AttrSet;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

/**
 * 图片编辑主控件
 * <p>
 * This ViewGroup will have the {@link BrushDrawingView} to draw paint on it with {@link Image}
 * which our source image
 *
 * @author xuexiang
 * @since 2019-10-28 10:29
 */
public class PhotoEditorView extends DependentLayout {
    static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x0021, "PhotoEditorView");
    private FilterImageView mImgSource;
    private BrushDrawingView mBrushDrawingView;
    private ImageFilterView mImageFilterView;
    private static final int IMG_SRC_ID = 1, BRUSH_SRC_ID = 2, GL_FILTER_ID = 3;
    private boolean isSaveIng;
    //private int vWidth;

    public PhotoEditorView(Context context) {
        super(context);
        init(null, context);
    }

    public PhotoEditorView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init(attrSet, context);
    }

    public PhotoEditorView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(attrSet, context);
    }

    /**
     * 初始化
     *
     * @param attrs 属性集合
     * @param context 上下文
     */
    private void init(AttrSet attrs, Context context) {
        //Setup image attributes
        mImgSource = new FilterImageView(context);
        mImgSource.setId(IMG_SRC_ID);
        mImgSource.setScaleMode(Image.ScaleMode.ZOOM_CENTER);

        LayoutConfig imgSrcParam = new LayoutConfig(
            LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
        mImgSource.setLayoutConfig(imgSrcParam);
        imgSrcParam.addRule(LayoutConfig.CENTER_IN_PARENT, LayoutConfig.TRUE);
        if (attrs != null) {
            PixelMapElement imgSrcDrawable = attrs.getAttr("photo_src").isPresent() ? (PixelMapElement) attrs.getAttr("photo_src").get().getElement() : null;
            if (imgSrcDrawable != null) {
                mImgSource.setPixelMap(imgSrcDrawable.getPixelMap());
            }
        }
        //Setup brush view
        mBrushDrawingView = new BrushDrawingView(context);
        mBrushDrawingView.setVisibility(HIDE);
        mBrushDrawingView.setId(BRUSH_SRC_ID);
        //Align brush to the size of image view
        LayoutConfig brushParam = new LayoutConfig(
            ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        brushParam.addRule(LayoutConfig.CENTER_IN_PARENT, LayoutConfig.TRUE);
        brushParam.addRule(LayoutConfig.ALIGN_TOP, IMG_SRC_ID);
        brushParam.addRule(LayoutConfig.ALIGN_BOTTOM, IMG_SRC_ID);
        //Setup GLSurface attributes
        mImageFilterView = new ImageFilterView(context);
        mImageFilterView.setId(GL_FILTER_ID);
        mImageFilterView.setVisibility(HIDE);
        //Align brush to the size of image view
        LayoutConfig imgFilterParam = new LayoutConfig(
            ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        imgFilterParam.addRule(LayoutConfig.CENTER_IN_PARENT, LayoutConfig.TRUE);
        imgFilterParam.addRule(LayoutConfig.ALIGN_TOP, IMG_SRC_ID);
        imgFilterParam.addRule(LayoutConfig.ALIGN_BOTTOM, IMG_SRC_ID);
        mImgSource.setOnImageChangedListener(new FilterImageView.OnImageChangedListener() {
            @Override
            public void onBitmapLoaded(PixelMap sourceBitmap) {
                HiLog.debug(TAG, "onBitmapLoaded() called with: sourceBitmap = [" + sourceBitmap + "]");
            }
        });
        //Add image source
        addComponent(mImgSource, imgSrcParam);
        //Add Gl FilterView

        //Add brush view
        addComponent(mBrushDrawingView, brushParam);

        setEstimateSizeListener(new EstimateSizeListener() {
            @Override
            public boolean onEstimateSize(int i, int i1) {
                int w = EstimateSpec.getSize(i);
                changeImaSize(w);
                return false;
            }
        });
    }

    /**
     * 获取画笔图层
     *
     * @return 画笔图层
     */
    public PixelMap getBrushPixelMap() {
        return getBrushDrawingView().getCanvasPixelMap();
    }

    private void changeImaSize(int width) {
        if (mImgSource != null) {
            //vWidth = width;
            Size size = mImgSource.getBitmap().getImageInfo().size;
            int height = width * size.height / size.width;
            PixelMap.InitializationOptions opt = new PixelMap.InitializationOptions();
            opt.size = new Size(width, height);
            PixelMap pixelMap = PixelMap.create(mImgSource.getPixelMap(), opt);
            mImgSource.setPixelMap(pixelMap);
        }
    }

    /**
     * Source image which you want to edit
     *
     * @return source ImageView
     */
    public Image getSource() {
        return mImgSource;
    }

    BrushDrawingView getBrushDrawingView() {
        return mBrushDrawingView;
    }

    void saveFilter(final OnBitmapSaveListener onBitmapSaveListener) {
        if (mImageFilterView.getVisibility() == VISIBLE) {
            mImageFilterView.saveBitmap(new OnBitmapSaveListener() {
                @Override
                public void onBitmapReady(final PixelMap saveBitmap) {
                    mImgSource.setPixelMap(saveBitmap);
                    mImageFilterView.setVisibility(HIDE);
                    onBitmapSaveListener.onBitmapReady(saveBitmap);
                }

                @Override
                public void onFailure(Exception e) {
                    onBitmapSaveListener.onFailure(e);
                }
            });
        } else {
            onBitmapSaveListener.onBitmapReady(mImgSource.getBitmap());
        }

    }

    void setFilterEffect(PhotoFilter filterType) {
        mImageFilterView.setVisibility(VISIBLE);
        mImageFilterView.setSourceBitmap(mImgSource.getBitmap());
        mImageFilterView.setFilterEffect(filterType);
    }

    void setFilterEffect(CustomEffect customEffect) {
        mImageFilterView.setVisibility(VISIBLE);
        mImageFilterView.setSourceBitmap(mImgSource.getBitmap());
        mImageFilterView.setFilterEffect(customEffect);
    }

    /**
     * 是否保存图片
     *
     * @return 是否保存
     */
    public boolean isSaveIng() {
        return isSaveIng;
    }

    /**
     * 设置保存图片状态
     *
     * @param saveIng 是否保存
     */
    public void setSaveIng(boolean saveIng) {
        isSaveIng = saveIng;
    }
}
